<?php

namespace app\admin\service;

use app\admin\model\UM as UM;
use app\common\model\Member;
use app\common\model\Transfer;
use app\common\service\TransfersServer;
use ShidianUtil\Exception\DataNotExistException;
use app\admin\dao\MemberInviteDao;
use app\common\model\MemberInvite;
use think\Collection;

/**
 * Class FixcardService
 * @package app\admin\service
 */
class FixcardService
{
    // dao
    private MemberInviteDao $memberInviteDao;

    public function __construct(MemberInviteDao $memberInviteDao)
    {
        $this->memberInviteDao = $memberInviteDao;
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return void
     */
    public function modify(UM $user, int $id, array $params): void
    {
        $record = MemberInvite::field(true)->where('memberIdInvite', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该邀请关系不存在或已被删除');
        }

        // 判断是否赠送了获客卡，没有赠送就补充赠送
        $card = Transfer::where('memberId', $record->memberId)
            ->where('inviteeId', $record->memberIdInvite)
            ->where('transferType', TRANSFER_CARD_INVITE)
            ->find();

        if(is_null($card)){

            // 给邀请人送 3 获客卡
            $describe = '邀请新用户奖励获客卡';
            $this->createTransfer($record->memberId, 3, $describe, $record->memberIdInvite);
        }
    }

    /**
     * 创建转账申请
     * @param $memberId
     * @param $card
     * @param $describe
     * @param $inviteeId
     * @return void
     */
    private function createTransfer($memberId, $card, $describe, $inviteeId)
    {
        $transferType = TRANSFER_CARD_INVITE;
        $payMethod = PAYMENT_CARD;
        $accountNumber = $memberId;
        $totalMoney = $card;
        $append = [
            'inviteeId' => $inviteeId,
        ];
        $this->getTransfersServer()->pushTransferToMember($transferType, $memberId, $payMethod, $accountNumber, $totalMoney, $describe, $append);
    }

    private function getTransfersServer(): TransfersServer
    {
        return app(TransfersServer::class);
    }
}
